package com.prizedraw.prize_draw.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.prizedraw.prize_draw.common.lang.Result;
import com.prizedraw.prize_draw.entity.SysRole;
import com.prizedraw.prize_draw.entity.SysRoleMenu;
import com.prizedraw.prize_draw.entity.SysUserRole;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  岗位控制层
 * </p>
 *
 * @author czj666
 * @since 2021-09-07
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    /**
     * 获取岗位
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id){
        SysRole sysRole=sysRoleService.getById(id);
        return Result.succ(sysRole);
    }

    /**
     * 岗位列表
     * @param name
     * @return
     */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public Result list(String name){
        Page<SysRole> pageDate = sysRoleService.page(getPage(),
                new QueryWrapper<SysRole>().like(StrUtil.isNotBlank(name), "name", name)
        );
        return Result.succ(pageDate);
    }

    /**
     * 添加岗位
     * @param sysRole
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:role:save')")
    public Result save(@RequestBody SysRole sysRole){
        sysRoleService.save(sysRole);
        return Result.succ("");
    }

    /**
     * 更新岗位
     * @param sysRole
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result update(@Validated @RequestBody SysRole sysRole){
        sysRoleService.updateById(sysRole);
        return Result.succ("");
    }

    /**
     * 删除岗位
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @Transactional
    public Result delete(@RequestBody Long[] ids){
        //删除角色表
        sysRoleService.removeByIds(Arrays.asList(ids));
        //删除角色-员工表
        for (Long id : ids) {
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("role_id",id));
        }

        return Result.succ("");
    }
}
